<template>
  <div id="panel">
    <template>
      <el-card class="queryForm">
        <el-form
          ref="queryForm"
          :model="queryParams"
          :inline="true"
          :label-position="'right'"
        >
          <el-form-item label="" prop="timeType">
            <el-radio-group
              v-model="queryParams.timeType"
              size="medium"
              @change="chosetime"
            >
              <el-radio-button
                v-for="option in timetypesel"
                :key="option.value"
                :label="option.value"
              >
                {{ option.label }}
              </el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="" prop="riverid">
            <el-form-item class="speItem">
              <el-date-picker
                popper-class="popperClass"
                v-model="startTime"
                :type="selectedType"
                :format="formatByType(queryParams.timeType)"
                placeholder="开始时间"
                :value-format="formatByType(queryParams.timeType)"
                @change="checkDuration"
                :clearable="false"
                :key="timer + 2"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item class="speItem">
              <el-date-picker
                popper-class="popperClass"
                v-model="endTime"
                :type="selectedType"
                :format="formatByType(queryParams.timeType)"
                style="margin-left: 10px"
                placeholder="结束时间"
                :value-format="formatByType(queryParams.timeType)"
                @change="checkDuration"
                :key="timer + 1"
                :clearable="false"
              >
              </el-date-picker>
            </el-form-item>
          </el-form-item>
          <el-form-item label="监测因子：" prop="segmentcategory" class="times">
            <el-select
              v-model="queryParams.segmentcategory"
              multiple
              collapse-tags
              placeholder="请选择"
            >
              <el-option
                v-for="item in options"
                :key="item.itemCode"
                :label="item.itemName"
                :value="item.itemCode"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              @click="handleQuery"
              style="padding: 10px"
              >查询</el-button
            >
            <el-button @click="resetQuery" style="padding: 10px">
              <i class="iconfont icon-saoba"></i>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
      <el-card class="pageContent">
        <div ref="charA" class="charA" v-if="isChartReady"></div>
      </el-card>
    </template>
  </div>
</template>

<script>
import * as echarts from "echarts";
import dayjs from "dayjs"; // 1. 引入day.js（需先安装：npm install dayjs --save）
import getTime from "@/utils/getTime.js";
import { updateDate, updateTime, updateTimeB } from "@/utils/ruoyi";
import { getTrendAnalysis } from "@/api/drinkingwatersource.js";
import { getFactorList } from "@/api/commonApi.js";

export default {
  name: "HydrologicStation",
  dicts: [
    "sys_segmenttype",
    "segment_prop",
    "sys_control_level",
    "sys_assse_type",
    "monitor_type_list",
    "monitor_targetlevel",
  ],
  props: ["selTreeId"],
  data() {
    return {
      timer: new Date().getTime(),
      selectedType: "datetime",
      startTime: "",
      endTime: "",
      loading: false,
      queryParams: {
        pageNum: 1,
        pageSize: 1000,
        timeType: "day",
        segmtype: "",
        segmentcategory: [],
        controllevelcode: "",
        assesstypecode: "",
        riverid: this.selTreeId,
      },
      timetypesel: [
        { value: "day", label: "日" },
        { value: "month", label: "月" },
      ],
      options: [],
      isFactorLoaded: false,
      chartInstance: null,
      isChartReady: false,
      factorColors: [
        "#FFB64D",
        "#4895EF",
        "#36CFC9",
        "#FF7A45",
        "#F08080",
        "#BC8F8F",
        "#6A5ACD",
        "#FFD700",
        "#ADD8E6",
        "#90EE90",
        "#9370DB",
        "#FF6347",
        "#20B2AA",
      ],
    };
  },
  watch: {
    selTreeId: {
      handler(newVal) {
        if (newVal) this.queryParams.riverid = newVal;
        this.checkAndFetchData();
      },
      immediate: true,
      deep: true,
    },
  },
  created() {
    this.getMonitorFactor();
    // 2. 初始化默认时间：最近15天（今天 - 14天 = 起始日，含今天共15天）
    this.endTime = dayjs().format("YYYY-MM-DD");
    this.startTime = dayjs().subtract(14, "day").format("YYYY-MM-DD");
  },
  mounted() {
    this.$nextTick(() => {
      this.isChartReady = true;
      this.initChart();
      window.addEventListener("resize", this.handleChartResize);
    });
  },
  beforeDestroy() {
    if (this.chartInstance) this.chartInstance.dispose();
    window.removeEventListener("resize", this.handleChartResize);
  },
  methods: {
    getMonitorFactor() {
      getFactorList({ bussinessCategoryCode: "Auto" }).then((res) => {
        this.options = res.data;
        this.queryParams.segmentcategory = res.data.map(
          (factor) => factor.itemCode
        );
        this.isFactorLoaded = true;
        this.checkAndFetchData();
      });
    },

    checkAndFetchData() {
      if (
        this.queryParams.riverid &&
        this.isFactorLoaded &&
        this.isChartReady
      ) {
        this.getList();
      }
    },

    checkDuration() {
      if (!this.startTime || !this.endTime) return;

      // 3. 使用day.js简化时间比较（替代原生Date）
      const start = dayjs(this.startTime);
      const end = dayjs(this.endTime);

      if (["minute", "real"].includes(this.queryParams.dataEnum)) {
        const maxDuration = 7 * 24 * 60 * 60 * 1000;
        // 用dayjs的diff方法计算时间差（单位：毫秒）
        if (end.diff(start, "millisecond") > maxDuration) {
          this.$message.error("时间范围不得超过7天");
          this.endTime = "";
          return;
        }
      }

      // 用dayjs的isAfter方法判断时间先后
      if (start.isAfter(end)) {
        this.$message.warning("开始时间不能大于结束时间");
        this.startTime = "";
      }
    },

    chosetime(val) {
      this.timer = new Date().getTime();
      this.formatByType(val);

      switch (val) {
        case "minute":
          this.startTime = `${dayjs().format("YYYY-MM-DD")} 00:00`; // 4. dayjs格式化日期
          this.endTime = updateTimeB();
          break;
        case "real":
          this.startTime = `${dayjs().format("YYYY-MM-DD")} 00:00:00`; // 4. dayjs格式化日期
          this.endTime = updateTime();
          break;
        case "hour":
          this.startTime = dayjs().format("YYYY-MM-DD"); // 4. dayjs格式化日期
          this.endTime = dayjs().format("YYYY-MM-DD"); // 4. dayjs格式化日期
          break;
        case "day":
          // 5. 核心修改：“日”类型默认最近15天
          this.endTime = dayjs().format("YYYY-MM-DD"); // 今天
          this.startTime = dayjs().subtract(14, "day").format("YYYY-MM-DD"); // 14天前
          break;
        case "month":
          // 6. 优化“月”类型时间：今年1月到当前月（用dayjs简化）
          this.startTime = dayjs().format("YYYY-01");
          this.endTime = dayjs().format("YYYY-MM");
          break;
        default:
          this.startTime = "";
          this.endTime = "";
      }
      this.handleQuery();
    },

    formatByType(type) {
      switch (type) {
        case "year":
          return "yyyy";
        case "month":
          return "yyyy-MM";
        case "day":
          return "yyyy-MM-dd";
        case "hour":
          return "yyyy-MM-dd HH";
        case "minute":
          return "yyyy-MM-dd HH:mm";
        case "real":
          return "yyyy-MM-dd HH:mm:ss";
        default:
          return "yyyy-MM-dd HH";
      }
    },

    initChart() {
      if (!this.$refs.charA) return;

      if (this.chartInstance) {
        this.chartInstance.dispose();
      }

      this.chartInstance = echarts.init(this.$refs.charA);
      this.chartInstance.setOption({
        title: {
          text: "断面变化趋势分析图",
          left: "center",
          textStyle: { fontSize: 16 },
        },
        tooltip: {
          trigger: "axis",
          axisPointer: { type: "cross" },
        },
        legend: { type: "scroll", right: 10, top: 30 },
        grid: {
          left: "5%",
          right: "15%",
          bottom: "15%",
          top: "15%",
          containLabel: true,
        },
        xAxis: { type: "category", data: ["暂无数据"] },
        yAxis: { type: "value" },
        series: [],
      });
    },

    handleChartResize() {
      if (this.chartInstance) this.chartInstance.resize();
    },

    // 核心修复：处理autoItemList为null/undefined的情况（保持原有逻辑不变）
    updateChart(apiData) {
      console.log("apiData", apiData);
      if (!this.chartInstance) {
        this.initChart();
        if (!this.chartInstance) return;
      }

      const safeData = apiData || {};
      const dateTime = Array.isArray(safeData.dateTime)
        ? safeData.dateTime
        : [];
      const itemList = Array.isArray(safeData.itemList)
        ? safeData.itemList
        : [];
      const xAxisData = dateTime.length > 0 ? dateTime : ["暂无数据"];
      const legendData = itemList.map((item) => item.itemName || "未知因子");
      const seriesConfig = [];

      const yAxisConfig = {
        type: "value",
        axisLine: { show: true, lineStyle: { color: "#666" } },
        splitLine: { show: true, lineStyle: { color: "#eee", type: "dashed" } },
      };

      itemList.forEach((factor, index) => {
        const safeFactor = factor || {};
        const itemName = safeFactor.itemName || `因子${index + 1}`;
        const unit = safeFactor.unit || "";
        const autoItemList = Array.isArray(safeFactor.autoItemList)
          ? safeFactor.autoItemList
          : [];
        const color = this.factorColors[index % this.factorColors.length];

        const seriesData = xAxisData.map((_, dtIndex) => {
          if (dtIndex >= autoItemList.length) return "-";
          const timePointData = autoItemList[dtIndex];
          if (!timePointData) return "-";
          const value = timePointData.effectiveValue;
          if (value === null || value === undefined) return "-";
          return typeof value === "number" ? Number(value.toFixed(2)) : "-";
        });

        seriesConfig.push({
          name: itemName,
          type: "line",
          data: seriesData,
          itemStyle: { color },
          lineStyle: { width: 2, color },
          symbol: "circle",
          symbolSize: 4,
          showSymbol: seriesData.some((v) => v !== "-"),
          emphasis: { symbolSize: 6 },
          connectNulls: false,
        });
      });

      if (itemList.length === 0) {
        seriesConfig.push({
          name: "无数据",
          type: "line",
          data: xAxisData.map(() => "-"),
          itemStyle: { color: "#ccc" },
          lineStyle: { color: "#ccc" },
        });
        legendData.push("无数据");
      }

      this.chartInstance.setOption({
        legend: { data: legendData },
        xAxis: {
          type: "category",
          data: xAxisData,
          axisLabel: { rotate: 45, interval: 0, fontSize: 10 },
        },
        yAxis: yAxisConfig,
        series: seriesConfig,
        tooltip: {
          formatter: (params) => {
            const validParams = params.filter((p) => p.value !== "-");
            if (validParams.length === 0) return "暂无数据";

            let html = `<div>${validParams[0].axisValue}</div>`;
            validParams.forEach((p) => {
              const unit =
                itemList.find((i) => (i?.itemName || "") === p.seriesName)
                  ?.unit || "";
              html += `<div style="display:flex;align-items:center;margin-top:4px">
                <span style="display:inline-block;width:12px;height:12px;background:${p.color};margin-right:6px"></span>
                <span>${p.seriesName}：${p.value} ${unit}</span>
              </div>`;
            });
            return html;
          },
        },
      });
    },

    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.queryParams.segmentcategory = [];
      // 7. 重置时同步使用最近15天（day.js实现）
      this.endTime = dayjs().format("YYYY-MM-DD");
      this.startTime = dayjs().subtract(14, "day").format("YYYY-MM-DD");
    },

    getList() {
      this.loading = true;
      const query = {
        itemCode: this.queryParams.segmentcategory.join(","),
        segmentId: this.queryParams.riverid,
        beginTime: this.startTime,
        endTime: this.endTime,
      };

      switch (this.queryParams.timeType) {
        case "hour":
          query.dataType = "1";
          break;
        case "day":
          query.dataType = "2";
          break;
        case "month":
          query.dataType = "3";
          break;
      }

      getTrendAnalysis(query)
        .then((res) => {
          this.loading = false;
          this.updateChart(res.data);
        })
        .catch((err) => {
          this.loading = false;
          console.error("数据请求失败:", err);
          this.updateChart({});
        });
    },
  },
};
</script>

<style lang="scss" scoped>
#panel {
  padding: 15px;
  min-height: calc(100% - 20px);
  .charA {
    width: 100%;
    height: 600px;
  }
  .queryForm {
    margin-bottom: 15px;
    padding: 10px;
  }
  .speItem {
    display: inline-block;
  }
}
</style>
